package cn.cloudplug.core.net.data;

import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;

import cn.cloudplug.core.index.Scent;
import cn.cloudplug.core.net.HttpMethod;
import cn.cloudplug.core.net.RestClient;
import cn.cloudplug.core.net.callback.IError;
import cn.cloudplug.core.net.callback.IFailure;
import cn.cloudplug.core.net.callback.ISuccess;
import retrofit2.Call;

/**
 * Created by pc on 2018/1/26.
 */

public class NetWorkData<T>{
    private DataConverter<T> dataConverter;
    private SoftReference<T> data;
    private LinkedHashMap<String,Object> params;
    private String url;

    public NetWorkData(String url, LinkedHashMap<String,Object> params,DataConverter<T> dataConverter) {
        this.url=url;
        this.params=params;
        this.dataConverter = dataConverter;
    }

    public void request(final Callback<T> callback) {
        if (data != null && data.get() != null) {
            Scent.mianHandler().post(new Runnable() {
                @Override
                public void run() {
                    callback.localLoad(data.get());
                }
            });
        } else {
            Scent.mianHandler().post(new Runnable() {
                @Override
                public void run() {
                    callback.localLoad(null);
                }
            });
        }
    }

    public void request(HttpMethod method, final Callback<T> callback){
        request(callback);
        RestClient.builder()
                .params(params)
                .url(url)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String body) {
                        callback.netWorkLoad(dataConverter.convert(body));
                    }
                })
                .failure(new IFailure() {
                    @Override
                    public void onFailure(Call<?> call, Throwable t) {
                        callback.error(-1,"failure",t);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String message) {
                        callback.error(code,message,null);
                    }
                })
                .build()
                .request(method);
    }

    interface Callback<T>{
        void localLoad(T data);
        void netWorkLoad(T data);
        void error(int code,String msg,Throwable throwable);
    }

}
